package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    @Scheduled(cron = "0 0/1 * * * ? ")
    public void processTimeoutOrder() {
        log.info("自动执行：处理支付超时订单");
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> list = ordersMapper.selectTimeOutOrder(Orders.PENDING_PAYMENT, time);

        if (list == null || list.size() == 0) return;

        log.info("查询到支付超时订单：{}", list);
        for (Orders order : list) {
            order.setStatus(Orders.CANCELLED);
            order.setCancelReason("订单超时，自动取消");
            order.setCancelTime(LocalDateTime.now());
            ordersMapper.update(order);
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        log.info("自动执行：处理派送中订单");
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> list = ordersMapper.selectTimeOutOrder(Orders.DELIVERY_IN_PROGRESS, time);

        if (list == null || list.size() == 0) return;

        log.info("查询到未处理派送中订单：{}", list);
        for (Orders order : list) {
            order.setStatus(Orders.COMPLETED);
            order.setDeliveryTime(time);
            ordersMapper.update(order);
        }

    }
}
